import re

from django.shortcuts import render, HttpResponse, redirect, reverse

# Create your views here.
# 登录认证, 登录用户可以继续操作, 其它都必须要先登陆
# from django.middleware.csrf import CsrfViewMiddleware

from django.utils.deprecation import MiddlewareMixin

LOGIN_URL = "/login/login"


class LoginCheck(MiddlewareMixin):
    def process_request(self, request):
        """
            1、获取到完整的路径，与正则路径匹配，如果完全符合则下一步
            2、获取到session是否登陆， 如果登陆也返回
            3、此时第1步，如果在跳转的时候一直匹配不上，则路径会一直进行拼接，此时获取一下next的路径如果有，也直接给它返回了
        """
        login_url = reverse("auth:login")
        next_path = request.get_full_path()
        next = request.GET.get("next")
        if re.match(next_path, login_url) or request.session.get("is_login") or next:
            print("匹配")
            return
        else:
            return redirect("/login/login?next={}".format(next_path))

    def process_response(self, request, response):
        return response


'''
    # url 后加 next跳转
    1、login页面获取next路径, 将路径传到 html页面
    2、页面获取到之后，拼接到 input中 以name方式在传输到后台
'''


def login(request):
    if request.method == "GET":
        next_path = request.GET.get("next")
        if next_path:
            return render(request, "login/login.html", {"next_path": next_path})
        return render(request, "login/login.html")

    if request.method == "POST":
        res = None
        name = request.POST.get("name")
        pwd = request.POST.get("pwd")
        next = request.POST.get("next_path")
        if name == "xiong" and pwd == "123":
            request.session["is_login"] = True
            print(next)
            if next:
                return redirect(next)
            res = "登陆成功"
        else:
            res = "登陆失败"
        return HttpResponse(res)


def buy(request):
    return HttpResponse("购物")
